package com.bxl.netty.rpc.common.pool;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <>
 *
 * @author baixl
 * @date 2021/3/8
 */
public class ThreadPoolUtil {
    private static ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 2, 3, TimeUnit.MINUTES, new LinkedBlockingQueue<Runnable>(10),
            new MyThreadFactory("executor"), new ThreadPoolExecutor.CallerRunsPolicy());

    private static ScheduledThreadPoolExecutor scheduled;

    static {
        scheduled = new ScheduledThreadPoolExecutor(1,
                new MyThreadFactory("scheduleAtFixedRate"), new ThreadPoolExecutor.CallerRunsPolicy());
        scheduled.setRemoveOnCancelPolicy(true);
    }

    static class MyThreadFactory implements ThreadFactory {
        private static final AtomicInteger poolNumber = new AtomicInteger(1);
        private final ThreadGroup group;
        private final AtomicInteger threadNumber = new AtomicInteger(1);
        private final String namePrefix;

        MyThreadFactory(String prefix) {
            SecurityManager s = System.getSecurityManager();
            group = (s != null) ? s.getThreadGroup() :
                    Thread.currentThread().getThreadGroup();
            namePrefix = prefix + "-" +
                    poolNumber.getAndIncrement() +
                    "-thread-";
        }

        public Thread newThread(Runnable r) {
            Thread t = new Thread(group, r,
                    namePrefix + threadNumber.getAndIncrement(),
                    0);
            if (t.isDaemon())
                t.setDaemon(false);
            if (t.getPriority() != Thread.NORM_PRIORITY)
                t.setPriority(Thread.NORM_PRIORITY);
            return t;
        }
    }

    public static void submit(Runnable r) {
        executor.submit(r);
    }

    /**
     * 延时定时执行
     *
     * @param r
     * @param initialDelay
     * @param period
     * @param unit
     * @return
     */
    public static ScheduledFuture scheduleAtFixedRate(Runnable r, long initialDelay,
                                                      long period,
                                                      TimeUnit unit) {
        return scheduled.scheduleAtFixedRate(new MyTask(r), initialDelay, period, unit);
    }

    /**
     * 只执行一次
     *
     * @param r
     * @param period
     * @param unit
     */
    public static void schedule(Runnable r,
                                long period,
                                TimeUnit unit) {
        scheduled.schedule(new MyTask(r), period, unit);
    }

    static class MyTask implements Runnable {
        private Runnable r;

        public MyTask(Runnable r) {
            this.r = r;
        }

        public void run() {
            executor.submit(r);
        }
    }

}
